﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite;
namespace StockTradTest.Data
{
    public class StockDatabase
    {
        readonly SQLiteAsyncConnection _database;

        public StockDatabase(string dbPath)
        {
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<Stock>().Wait();
            
        }
        public Task<Stock> GetStockAsync(int date)
        {
            return _database.Table<Stock>()
                            .Where(i =>i.Date == date)
                            .FirstOrDefaultAsync();
        }

        public Task<Stock> GetStockAsync(string code,int date)
        {
            Base.CurrentCode = code;
            return Base.StockDatabase.GetStockAsync(date);
        }
        public Task<List<Stock>> GetStockAsync(int startDate = 0, int endDate = int.MaxValue)
        {
            if(endDate == int.MaxValue  & startDate == 0)
            {
                return _database.Table<Stock>().
                ToListAsync();
            }
            return _database.Table<Stock>().
                Where(i => i.Date > startDate & i.Date < endDate).
                ToListAsync();
        }
        //股票顺序为0-count：最旧-最新
        public async Task<int> SaveAllStockAsync(List<Stock> stocks)
        {
            if (stocks == null || stocks.Count == 0) return 0;
            //数据库中该股票信息
            List<Stock> checkStocks = GetStockAsync().Result;
            if(checkStocks == null || checkStocks.Count == 0)
            {
                return await _database.InsertAllAsync(stocks);
            }
            //数据库中最新的日期股票信息
            Stock upToDateStock = checkStocks[checkStocks.Count - 1];
            //从最新日期开始计算
            for (int i= 0; i < stocks.Count;i++)
            {
                //从最新的开始比对
                if (stocks[i].Date == upToDateStock.Date) 
                {
                    if(stocks[i].ClosePrice == upToDateStock.ClosePrice)
                        return await _database.InsertAllAsync(stocks.GetRange(i + 1,stocks.Count - i-1));
                    else
                    {
                        await _database.Table<Stock>().DeleteAsync();
                        return await _database.InsertAllAsync(stocks);
                    }
                }
            }
            return await _database.InsertAllAsync(stocks);
        }

        public Task<int> DeleteStockAsync(Stock stock)
        {
            return _database.DeleteAsync(stock);
        }
    }
}
